
import java.io.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;

public class Utils {

    public static String ByteToString(byte[] block) throws Exception {
        return new String(block, "UTF8");
    }

    public static byte[] getFileBytes(String fileName) throws FileNotFoundException, IOException {
        File file = new File(fileName);
        InputStream is = new FileInputStream(file);
        if (is.available() > 0) {
            System.out.println("Good to Go \n");
        } else {
            System.out.println("fail \n");
        }
        int fileLength = (int) file.length();
        System.out.println("length = " + fileLength);
        byte[] fileBytes = new byte[fileLength];
        int offset = 0;
        int numRead = 0;

        numRead = is.read(fileBytes, offset, fileBytes.length - offset);
        offset += numRead;
        System.out.println("numRead = " + numRead + "\n");

        if (offset < fileBytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        return fileBytes;
    }

    public static void writeFile(String fileName, byte[] text) throws FileNotFoundException, IOException {
        File newFile = new File(fileName);
        OutputStream os = new FileOutputStream(newFile);
        os.write(text);
        os.close();
    }

    public static String ByteToBitString(byte[] b) {
        String binary = "";
        for (int i = 0; i < b.length; i++) {
            String separator = " ";
            if (i == 0) {
                separator = "";
            }

            binary = binary + separator + Integer.toBinaryString(b[i] & 0xFF);
        }
        return binary;
    }

    public static String GetUserInput(String display) throws Exception {
        InputStreamReader inStream = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(inStream);
        System.out.print(display);
        return in.readLine();
    }

    public static String ToHexString(byte[] ba) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < ba.length; i++) {
            str.append(String.format("%x", ba[i]));
        }
        return str.toString();
    }

    public static byte[] Hash(byte[] b) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return md.digest(b);
    }

    public static byte[] HMAC(byte[] key, byte[] data) throws Exception {
        // Get an hmac MD5 key from key bytes          
        SecretKeySpec sKey = new SecretKeySpec(key, "HmacMD5");

        // Get an hmacMD5 Mac instance and initialize with the key
        Mac mac = Mac.getInstance(sKey.getAlgorithm());
        mac.init(sKey);

        // Compute the hmac on input data bytes
        byte[] HMAC = mac.doFinal(data);

        return HMAC;
    }
}
